/**
 * 认证相关的组合式API
 */
import { ref, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 全局加载状态
const isInitializing = ref(false)
const initializationError = ref<string | null>(null)

export function useAuth() {
  const userStore = useUserStore()
  const router = useRouter()

  // 计算属性
  const isLoggedIn = computed(() => userStore.isLoggedIn)
  const userInfo = computed(() => userStore.userInfo)
  const isLoading = computed(() => isInitializing.value)
  const hasError = computed(() => !!initializationError.value)

  // 初始化认证状态
  const initAuth = async () => {
    if (isInitializing.value) return

    isInitializing.value = true
    initializationError.value = null

    try {
      // 如果有token但没有用户信息，尝试获取
      if (userStore.token && !userStore.userInfo) {
        await userStore.initUserInfo()
      }
    } catch (error: any) {
      console.error('认证初始化失败:', error)
      initializationError.value = error.message || '认证初始化失败'
      
      // 如果是token相关错误，清除认证信息
      if (error.response?.status === 401) {
        userStore.clearToken()
        userStore.clearUserInfo()
      }
    } finally {
      isInitializing.value = false
    }
  }

  // 检查路由权限
  const checkRoutePermission = (route: any): boolean => {
    // 不需要认证的路由
    if (!route.meta?.requiresAuth) {
      return true
    }

    // 需要认证但未登录
    if (!isLoggedIn.value) {
      return false
    }

    // 检查角色权限
    if (route.meta?.roles && Array.isArray(route.meta.roles)) {
      const userRole = userInfo.value?.role
      if (!userRole || !route.meta.roles.includes(userRole)) {
        return false
      }
    }

    return true
  }

  // 安全导航
  const navigateTo = async (path: string) => {
    try {
      // 确保认证状态已初始化
      if (!userStore.userInfo && userStore.token) {
        await initAuth()
      }

      await router.push(path)
    } catch (error: any) {
      console.error('导航失败:', error)
      ElMessage.error('页面跳转失败')
    }
  }

  // 登录
  const login = async (credentials: any) => {
    isInitializing.value = true
    initializationError.value = null

    try {
      await userStore.login(credentials)
      ElMessage.success('登录成功')
      return true
    } catch (error: any) {
      console.error('登录失败:', error)
      initializationError.value = error.message || '登录失败'
      ElMessage.error(error.message || '登录失败')
      return false
    } finally {
      isInitializing.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      await userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/login')
    } catch (error: any) {
      console.error('登出失败:', error)
      ElMessage.error('登出失败')
    }
  }

  // 刷新认证状态
  const refreshAuth = async () => {
    if (userStore.token) {
      await initAuth()
    }
  }

  // 清除错误状态
  const clearError = () => {
    initializationError.value = null
  }

  return {
    // 状态
    isLoggedIn,
    userInfo,
    isLoading,
    hasError,
    error: computed(() => initializationError.value),

    // 方法
    initAuth,
    checkRoutePermission,
    navigateTo,
    login,
    logout,
    refreshAuth,
    clearError
  }
}

// 全局认证状态
export const globalAuth = {
  isInitializing: computed(() => isInitializing.value),
  initializationError: computed(() => initializationError.value),
  
  setInitializing: (value: boolean) => {
    isInitializing.value = value
  },
  
  setError: (error: string | null) => {
    initializationError.value = error
  }
}
